<script setup lang="ts">
import { register, type RegisterResponse } from '@/api/login/login'
import type { FormInstance, FormItemRule } from 'element-plus'

const formRef = ref<FormInstance>()

interface ResponseMsg extends RegisterResponse {
  errorDetails?: {
    type: string
    description: string
  }
}

const responseMsg = ref<ResponseMsg>()
const showSuccessMsg = ref(false)
const showErrorMsg = ref(false)

const form = ref({
  id_last_six: '',
  name: '',
  gender: '',
  dominant_hand: '',
  diagnosis: '',
  dob: '',
  height_cm: void 0,
  weight_kg: void 0,
  contact: '',
  education_level: '',
  education_years: void 0,
  remarks: '',
})

const largerThanZero = (errMsg: string) => {
  return (_rule: unknown, value: number, callback: (error?: string | Error) => void) => {
    if (!value || value <= 0) {
      callback(new Error(errMsg))
    } else {
      callback()
    }
  }
}

const rules = ref<Record<string, FormItemRule | Array<FormItemRule>>>({
  id_last_six: { required: true, message: '请输入身份证号后六位', trigger: 'change' },
  name: { required: true, message: '请输入姓名', trigger: 'change' },
  gender: { required: true, message: '请选择性别', trigger: 'change' },
  dominant_hand: { required: true, message: '请选择利手', trigger: 'change' },
  diagnosis: { required: true, message: '请输入诊断', trigger: 'change' },
  dob: { required: true, message: '请选择出生年月', trigger: 'change' },
  height_cm: [
    { required: true, message: '请输入身高', trigger: 'change' },
    { trigger: 'change', validator: largerThanZero('身高必须大于0') },
  ],
  weight_kg: [
    { required: true, message: '请输入体重', trigger: 'change' },
    { trigger: 'change', validator: largerThanZero('体重必须大于0') },
  ],
  contact: { required: true, message: '请输入联系方式', trigger: 'change' },
})

const disabledDate = (date: Date) => {
  const today = new Date()
  return date.getTime() > today.getTime()
}

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return false

  // 重置消息状态
  showSuccessMsg.value = false
  showErrorMsg.value = false

  const params = {
    ...form.value,
    height_cm: form.value.height_cm || 0,
    weight_kg: form.value.weight_kg || 0,
    education_years: form.value.education_years || 0,
  }

  try {
    const response = await register(params)
    if (response?.data) {
      responseMsg.value = response
      showSuccessMsg.value = true
    }
  } catch (error: any) {
    responseMsg.value = error
    showErrorMsg.value = true
  }
}

const genderFormatter = (gender = '') => {
  if (gender === 'male') {
    return '男'
  } else if (gender === 'female') {
    return '女'
  } else {
    return gender
  }
}
</script>

<template>
  <div class="h-full overflow-auto bg-brand p-6">
    <h1 class="text-3xl font-bold text-white text-center">智能评估系统</h1>
    <p class="text-center text-12px text-#A6CFD5 my-4">
      注：请填写真实信息，信息影响将影响检测结果
    </p>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="90px"
      hide-required-asterisk
      @submit.prevent="handleSubmit"
    >
      <el-form-item label="身份证号：" prop="id_last_six">
        <el-input v-model.trim="form.id_last_six" placeholder="请输入身份证号后六位" />
      </el-form-item>
      <el-form-item label="姓名：" prop="name">
        <el-input v-model.trim="form.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="性别：" prop="gender">
        <el-select
          v-model="form.gender"
          placeholder="请选择性别"
          :empty-values="[null, undefined, '']"
        >
          <el-option label="请选择" value="" />
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="利手：" prop="dominant_hand">
        <el-select
          v-model="form.dominant_hand"
          placeholder="请选择利手"
          :empty-values="[null, undefined, '']"
        >
          <el-option label="请选择" value="" />
          <el-option label="左手" value="左手" />
          <el-option label="右手" value="右手" />
        </el-select>
      </el-form-item>
      <el-form-item label="诊断：" prop="diagnosis">
        <el-input v-model.trim="form.diagnosis" placeholder="请输入诊断" />
      </el-form-item>
      <el-form-item label="出生年月：" prop="dob">
        <el-date-picker
          v-model="form.dob"
          type="date"
          date-format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
          placeholder="请选择出生年月"
          class="w-full!"
        />
      </el-form-item>
      <el-form-item label="身高：" prop="height_cm">
        <div class="flex items-center w-full">
          <el-input-number
            v-model.number="form.height_cm"
            :controls="false"
            align="left"
            placeholder="请输入身高"
            class="mr-2 flex-1 min-w-0"
          />
          <span class="font-bold text-white">CM</span>
        </div>
      </el-form-item>
      <el-form-item label="体重：" prop="weight_kg">
        <div class="flex items-center w-full">
          <el-input-number
            v-model.number="form.weight_kg"
            :controls="false"
            align="left"
            placeholder="请输入体重"
            class="mr-2 flex-1 min-w-0"
          />
          <span class="font-bold text-white">KG</span>
        </div>
      </el-form-item>
      <el-form-item label="联系方式：" prop="contact">
        <el-input v-model.trim="form.contact" placeholder="请输入联系方式" />
      </el-form-item>
      <el-form-item label="教育程度：" prop="education_level">
        <el-input v-model.trim="form.education_level" placeholder="请输入教育程度" />
      </el-form-item>
      <el-form-item label="教育年限：" prop="education_years">
        <el-input-number
          v-model.number="form.education_years"
          :controls="false"
          align="left"
          placeholder="请输入教育年限"
          class="w-full!"
        />
      </el-form-item>
      <el-form-item label="备注：" prop="remarks">
        <el-input
          v-model.trim="form.remarks"
          type="textarea"
          :autosize="{ minRows: 4 }"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-form-item label-width="0" class="register-button-wrapper">
        <el-button native-type="submit" class="brand-dark-button py-5! w-full">完成注册</el-button>
      </el-form-item>
      <el-form-item label-width="0">
        <!-- 成功消息 -->
        <div v-if="showSuccessMsg" class="mt-2 w-full result success">
          <h3>✅ 患者注册成功！</h3>

          <div class="patient-info">
            <h4>患者信息：</h4>
            <p><strong>姓名：</strong> {{ responseMsg?.data?.name }}</p>
            <p><strong>病历号：</strong> {{ responseMsg?.data?.medical_record_number }}</p>
            <p><strong>身份证后六位：</strong> {{ responseMsg?.data?.id_last_six }}</p>
            <p>
              <strong>性别：</strong>
              {{ genderFormatter(responseMsg?.data?.gender) }}
            </p>
            <p><strong>出生日期：</strong> {{ responseMsg?.data?.dob }}</p>
            <p><strong>诊断：</strong> {{ responseMsg?.data?.diagnosis }}</p>
          </div>

          <div class="qr-section">
            <h4>登录二维码：</h4>
            <div class="qr-code-container">
              <img :src="responseMsg?.data?.login_qr_code" alt="登录二维码" class="qr-code" />
              <p class="text-sm mt-2 text-center">请使用此二维码进行登录</p>
            </div>
          </div>
        </div>

        <!-- 失败消息 -->
        <div v-if="showErrorMsg" class="mt-2 w-full result error">
          <h3>❌ 注册失败</h3>
          <p>
            <strong>错误信息:</strong>
            {{ responseMsg?.errorDetails?.description || responseMsg?.message || '未知错误' }}
          </p>
          <p><strong>状态码:</strong> {{ responseMsg?.code }}</p>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="css" scoped>
:deep(.el-form-item::after) {
  content: '*';
  position: relative;
  top: 6px;
  right: -12px;
  color: transparent;
}
:deep(.is-required::after) {
  color: red;
}
:deep(.el-form-item__label) {
  color: #fff !important;
  font-weight: 600 !important;
}
:deep(.el-button--primary) {
  --el-button-border-color: #fff;
  --el-button-hover-border-color: #fff;
  font-weight: 600;
}
:deep(.register-button-wrapper .el-form-item__content) {
  justify-content: center;
}

/* 结果消息样式 */
.result {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid;

  h3 {
    margin: 0 0 12px 0;
    font-size: 18px;
    font-weight: bold;
  }

  h4 {
    margin: 16px 0 8px 0;
    font-size: 16px;
    font-weight: 600;
  }

  p {
    margin: 8px 0;
    line-height: 1.5;

    strong {
      font-weight: 600;
    }
  }
}

.result.success {
  background-color: rgba(240, 249, 255, 0.9);
  border-color: #22c55e;
  color: #065f46;

  h3,
  h4 {
    color: #059669;
  }
}

.result.error {
  background-color: rgba(254, 242, 242, 0.9);
  border-color: #ef4444;
  color: #991b1b;

  h3 {
    color: #dc2626;
  }
}

/* 患者信息区域 */
.patient-info {
  background-color: rgba(255, 255, 255, 0.8);
  padding: 12px;
  border-radius: 6px;
  margin: 12px 0;
  border: 1px solid rgba(34, 197, 94, 0.2);
}

/* 二维码区域 */
.qr-section {
  text-align: center;
  margin-top: 16px;
}

.qr-code-container {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 16px;
  border-radius: 8px;
  border: 1px solid rgba(34, 197, 94, 0.2);
  display: inline-block;
  margin-top: 8px;
}

.qr-code {
  max-width: 200px;
  max-height: 200px;
  width: auto;
  height: auto;
  border: none;
}
</style>
